﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.OfficeArt
{
    internal partial class OfficeArtFDGGBlock : OfficeArtRecord
    {
        private readonly List<OfficeArtIDCL> Rgidcl = new List<OfficeArtIDCL>();
        private OfficeArtFDGG _head = new OfficeArtFDGG();

        public override RecType RecordType
        {
            get
            {
                Contract.Ensures(GetType().Name == Contract.Result<RecType>().ToString());
                Contract.Assert(GetType().Name == RecType.OfficeArtFDGGBlock.ToString());
                return RecType.OfficeArtFDGGBlock;
            }
        }



        protected override void ReadNoHeader(OfficeArtReadContext context)
        {
            Contract.Assert(rhrecVer == 0x0);
            Contract.Assert(rhrecInstance
                            == 0x000);
            Contract.Assert(rhrecType
                            == RecType.OfficeArtFDGGBlock);
            _head = new OfficeArtFDGG();
            _head.Read(context.Reader);
            Contract.Assert(rhrecLen == 0x00000010 + ((_head.cidcl - 1) * 0x00000008));
            Rgidcl.Clear();
            for (int i = 0; i < _head.cidcl - 1; i++)
            {
                var item = new OfficeArtIDCL();
                item.Read((context.Reader));
                Rgidcl.Add((item));
            }
        }

        protected override byte Version
        {
            get { return 0; }
        }

        protected override int ByteLength
        {
            get { return OfficeArtFDGG.ByteLength + Enumerable.Sum(Rgidcl, item => OfficeArtIDCL.ByteLength); }
        }


        protected override void WriteNoHeader(OfficeArtWriteContext context)
        {
            Contract.Assert(rhrecVer == 0x0);
            Contract.Assert(rhrecInstance == 0x000);
            Contract.Assert(rhrecType == RecType.OfficeArtFDGGBlock);
            Contract.Assert(Rgidcl.Count == _head.cidcl - 1);
            _head.Write(context.Writer);
            foreach (OfficeArtIDCL item in Rgidcl)
                item.Write(context.Writer);
        }

        protected override void PrepareHeader(ref OfficeArtRecordHeader rh)
        {
            rh.recInstance = 0;
            _head.cidcl = (uint)(Rgidcl.Count + 1);
        }
        public void Prepare()
        {
            Rgidcl.Add(new OfficeArtIDCL(2, 1));
            _head.spidMax = 2029;//\\
            _head.cdgSaved = 1;
            _head.cspSaved = 2;

        }
    }
}